package com.stanwind.netty.handler.impl;

import com.stanwind.netty.api.CardUtils;
import com.stanwind.netty.api.ClientUtils;
import com.stanwind.netty.api.Log;
import com.stanwind.netty.api.RoomUtils;
import com.stanwind.netty.constant.CardType;
import com.stanwind.netty.constant.GameStep;
import com.stanwind.netty.constant.ServerSetting;
import com.stanwind.netty.core.protocol.model.Response;
import com.stanwind.netty.domain.pojo.Card;
import com.stanwind.netty.domain.pojo.Player;
import com.stanwind.netty.domain.pojo.Room;
import com.stanwind.netty.handler.Handler;
import com.stanwind.netty.serialize.PayCard;
import com.stanwind.netty.serialize.ShowCards;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

/**
 * Created by StanWind on 2017/2/25.
 */
@Service
@Scope("prototype")
public class PAYCARD extends Handler {
    @Autowired
    private Log log;

    @Autowired
    private ClientUtils clientUtils;

    @Autowired
    private RoomUtils roomUtils;


    @Override
    public void handle() {
        Player player = clientUtils.getPlayer(getCtx().getChannel().getId());
        if (player == null)
            return;
        //获取玩家房间步骤
        Room room = roomUtils.getRoomByRoomId(player.getRoomId());
        GameStep gameStep = room.getGameStep();
        if (!room.getCurrentPlayer().equals(player)) {
            log.getLogger().info("【出牌】不是当前玩家操作 -> " + player.getCharacter().getNickname());
            return;
        }

        //取消上次任务
        if (room.getTimer() != null)
            room.getTimer().cancel();
        room.setTimer(new Timer());


        //  1. 收到牌 先看是不是有这些牌
        //  2. 再校验牌型 是否有效 是否翻倍
        //  3. 再与上家比较
        //  4. 出牌 判断剩余张数是否结束

        //拿出出牌
        PayCard payCard = new PayCard();
        payCard.readFromBytes(getRequest().getData());
        List<Card> payCards = payCard.getPayCards();
        if (payCards.size() == 0) {
            System.err.println("不要");
            //玩家不要
            Player nextPlayer = room.getNextPlayer();
            room.setCurrentPlayer(nextPlayer);
            if (nextPlayer.equals(room.getLastPlayer())) {
                //没人要
                room.setGameStep(GameStep.PAY_CARD);
                //TODO TIMER
                log.getLogger().error("一圈没人要 重新出牌");

            } else {
                room.setGameStep(GameStep.EAT_CARD);
                //TODO  TIMER
                log.getLogger().error("不要 下家吃牌");
            }
            roomUtils.sendStep(room, nextPlayer.getCharacter().getAccountId(), ServerSetting.EAT_CARD_TIME);
            return;
        }

        System.err.println(player.getCharacter().getNickname()+" -> "+payCards);
        //1.
        if (!player.getHandCards().containsAll(payCards)) {
            log.getLogger().error("要出的手牌不存在->" + payCards);
            return;
        }

        //2.
        CardType cardType = CardUtils.getCardType(payCards);
        switch (cardType) {
            //TODO 炸弹翻2倍
            case BOMB_CARD:   //炸弹（四张）
            case KING_BOMB_CARD:     //王炸
                room.setRate(room.getRate() * 2);
                break;
            case ERROR_CARD:          //错误类型
                log.getLogger().error("牌型错误->" + payCards);
                return;
            default:
                //其他牌型 不翻倍
                break;
        }

        //3.先判断是不是主动出牌
        if (gameStep.getValue() == GameStep.EAT_CARD.getValue()) {
            //与上家比较牌型 是否要的起
            if (!CardUtils.isOvercomePrev(payCards, room.getLastCards())) {
                log.getLogger().error("要不起对方的牌 我的->" + payCard + "  上家->" + room.getLastCards());
                payCard.setPayCards(new ArrayList<>());     //  要不起置为空
            }
        } else if (gameStep.getValue() == GameStep.PAY_CARD.getValue()) {
            room.setGameStep(GameStep.EAT_CARD);
        }

        //4.不比较上家牌型
        if (payCard.getPayCards().size() != 0) {
            //说明玩家要牌 更新位置
            room.setLastCards(payCards);                                //  记录上次出牌
            room.setLastPlayer(player);                                 //  记录上次出牌玩家
            player.getHandCards().removeAll(payCards);                  //  移除玩家手牌
        }
        payCard.setAccountId(player.getCharacter().getAccountId());     //  设置出手玩家accountID
        payCard.setRate(room.getRate());                                //  更新倍率
        Response response = new Response();
        response.setCmd(CMD_PAYCARD);
        response.setData(payCard.getBytes());
        roomUtils.boardResponse(room, response);

        // 5.判断玩家手牌张数 看是不是推给下个人 或者 结束
        if (player.getHandCards().size() == 0) {
            //  显示所有玩家手牌
            roomUtils.sendAllPlayerCards(room);
            //  金币结算
            // TODO  底分 10分    房费250
            int gold = 10*room.getRate();
            if(player.equals(room.getLandlord())){
                log.getLogger().error("地主胜利->" + player.getCharacter().getNickname());
                for(Player p:room.getPlayers()){
                    if(!p.equals(room.getLandlord())){
                        //不是庄家
                        p.setChangedGolds(-250-1*gold);
                    }else{
                        p.setChangedGolds(-250+gold*2);
                    }
                }
            }else{
                log.getLogger().error("农民胜利->" + player.getCharacter().getNickname());
                for(Player p:room.getPlayers()){
                    if(!p.equals(room.getLandlord())){
                        //不是庄家
                        p.setChangedGolds(-250+1*gold);
                    }else{
                        p.setChangedGolds(-250-2*gold);
                    }
                }
            }
            roomUtils.sendAllPlayerChangeGolds(room);   //  发送变更
            roomUtils.saveAllPlayerChangeGolds(room);   //  保存变更


            //  重置房间
            room.resetRoom();
            //结束
        } else {
            Player nextPlayer = room.getNextPlayer();
            room.setCurrentPlayer(nextPlayer);
            //TODO TIMER
            roomUtils.sendStep(room, nextPlayer.getCharacter().getAccountId(), ServerSetting.EAT_CARD_TIME);
        }
    }



}
